const path = require('path');
const express = require('express');
// swig前端模板引擎
// const swig = require('swig');
// body-parser解析http请求
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// 按需跨域处理
// const cors = require('cors');
const Cookies = require('cookies');

let app = express();

// 
// app.use(cors());

// 视图引擎设置
// app.engine('html', swig.renderFile)
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'html')

// 开发过程中取消缓存
// swig.setDefaults({cache: false});

// cookies设置
// app.use((req, res, next) => {
//     req.cookies = new Cookies(req, res);

//     if(req.cookies.get('user')) {

//     } else {

//     }

//     next();
// });

app.use((req, res, next) => {
    req.cookies = new Cookies(req, res);
    // userInfo = req.cookies.get('userInfo') ? JSON.parse(req.cookies.get('userInfo')) : userInfo;
    next();
});

// body-parser设置
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 功能模块化
// app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
app.use('/goods', require('./routes/goods'));

app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (req.method == 'OPTIONS') {
        res.send(200);
        /*让options请求快速返回*/
    } else {
        next();
    }
});

/** 连接数据库 */
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/mkMall', { useMongoClient: true }, err => {
    if(err) throw err;
    app.listen(9090);
    console.log('mkMall connect success');
});

module.exports = app;